package ua.cs.stu.ics.print;

import ua.cs.stu.ics.GUI.ImagePanel;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.IOException;

/**
 * author: evgeniy
  */
public class Printer {

    public static void printComponenet(final ImagePanel imagePanel) {
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(OrientationRequested.LANDSCAPE);
        aset.add(new MediaPrintableArea(0, 0, 210, 297, MediaPrintableArea.MM));
        aset.add(new Copies(1));
        aset.add(new JobName("My job", null));

        PrinterJob pj = PrinterJob.getPrinterJob();
        pj.setJobName(" Print Component ");

        pj.setPrintable(new Printable() {
            public int print(Graphics pg, PageFormat pf, int pageNum) {
                if (pageNum > 0) {
                    return Printable.NO_SUCH_PAGE;
                }
                Graphics2D g2 = (Graphics2D) pg;
                BufferedImage bi = ScreenImage.createImage(imagePanel);
                try {
                    ScreenImage.writeImage(bi, "panel.png");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                g2.drawImage(bi, null, 0, 0);
                return Printable.PAGE_EXISTS;
            }
        });
        PrintService[] services = PrinterJob.lookupPrintServices();

        if (services.length > 0) {
            System.out.println("selected printer " + services[0].getName());
            try {
                pj.setPrintService(services[0]);
                pj.pageDialog(aset);
                if (pj.printDialog(aset)) {
                    pj.print(aset);
                }

            } catch (PrinterException pe) {
                System.err.println(pe);
            }
        }
    }
}
